package playlistData;

import java.io.File;

import xml.INodeRemover;
import xml.IReader;
import xml.IWriter;
import xml.NodeRemover;
import xml.NodeUtilities;
import xml.Reader;
import xml.Writer;

public class ListManager {

	private String listpath;
	private static ListManager listManager = new ListManager();
	private IReader reader;
	private IWriter writer;
	private PlaylistMap map;
	private INodeRemover remover;

	private ListManager() {
		reader = new Reader();
		writer = new Writer();
		remover = new NodeRemover();
		listpath = NodeUtilities.defaultPlaylist;
		refreshMap();
	}

	/**
	 * 
	 * @return listManager
	 */
	public static ListManager getListManager() {
		return listManager;
	}

	private void refreshMap() {
		try {
			if (map == null) {
				map = new PlaylistMap(reader.getPathFromXML(listpath));
			} else {
				map.loadPlaylist(reader.getPathFromXML(listpath));
			}
		} catch (Exception e) {

		}
	}

	/**
	 * 
	 * @return map
	 */
	public PlaylistMap getMap() {
		return map;
	}

	/**
	 * Aggiunge una plalist e la sua directory
	 * 
	 * @param name
	 * @param path
	 */
	void addPlaylist(String name, String path) {
		String fullPath = path + "/" + name + ".xml";
		writer.writeNodeToXML(fullPath, "name", "value");
		remover.removeNode(fullPath, "value");
		writer.writeNodeToXML(NodeUtilities.defaultPlaylist, fullPath, name);
		refreshMap();
	}

	/**
	 * Rimuove una playlist
	 * 
	 * @param name
	 */
	public void removePlaylist(String name) {
		try {
			PlaylistMap map = new PlaylistMap(
					reader.getPathFromXML(NodeUtilities.defaultPlaylist));
			String path = map.getPathByName(name);
			remover.removeNode(NodeUtilities.defaultPlaylist, name);
			File f = new File(path);
			refreshMap();
			f.delete();
		} catch (Exception e) {

		}
	}

	/**
	 * Rinonima una playlist
	 * 
	 * @param name
	 * @param newName
	 * @param newPath
	 */
	public void renamePlaylist(String name, String newName, String newPath) {
		try {
			String fullNewPath = newPath + "/" + newName + ".xml";
			PlaylistMap map = new PlaylistMap(
					reader.getPathFromXML(NodeUtilities.defaultPlaylist));
			String path = map.getPathByName(name);
			File f = new File(path);
			File newFile = new File(fullNewPath);
			f.renameTo(newFile);
			remover.removeNode(NodeUtilities.defaultPlaylist, name);
			addPlaylist(newName, NodeUtilities.defaultPlaylistLocation);
			refreshMap();
		} catch (Exception e) {

		}
	}
}
